package test;

import sun.font.FontRunIterator;
import sun.nio.cs.ext.IBM037;

/**
 * 描述：
 * 判断在一个矩阵中是否存在一条包含某字符串所有字符的路径
 *
 * @author hl
 * @version 1.0
 * @date 2020/11/6 9:29
 */
public class MatrixPath {
    public static void main(String[] args) {
//        char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
//        String word = "ABCCED";
        char[][] board = {{'a','b'},{'c','d'}};
        String word = "abcd";
        System.out.println(new MatrixPath().exist(board, word));
    }
    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (isPath(i, j, board, word, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean isPath(int i, int j, char[][] board, String word, int n) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[i].length || board[i][j] != word.charAt(n)) {
            return false;
        }
        if (n == word.length() - 1) {
            return true;
        }
        char temp = board[i][j];
        board[i][j] = '/';
        boolean res = isPath(i - 1, j, board, word, n + 1)
                    || isPath(i + 1, j, board, word, n + 1)
                    || isPath(i, j - 1, board, word, n + 1)
                    || isPath(i, j + 1, board, word, n + 1);
        return res;
    }
}
